import 'dart:async';

import 'package:get/get.dart';
import 'package:wechat_kit/wechat_kit.dart';
import 'package:wechat_kit_extension/wechat_kit_extension.dart';
import 'package:zrjz/comm/utils/log_utils.dart';

typedef WXInfoCallback = void Function(String openId);

class WXPlatformService extends GetxService {
  static WXPlatformService get to => Get.find();

  String kWechatAppID = 'wx12345678';
  String kWechatAppSecret = 'xxxxxxxx';
  String kWechatUniversalLink = 'https://xxxxxxxx/'; // iOS 请配置

  StreamSubscription<WechatResp>? _respSubs; //标记是否已经初始化
  WechatAuthResp? _authResp;

  //回调详情数据
  WXInfoCallback? mWXInfoCallback;

  /// 服务初始化的时候，构造创建
  Future<void> _initWX() async {
    Log.d('初始化WX平台SDK');
    _respSubs = WechatKitPlatform.instance.respStream().listen(_listenResp);

    //向微信注册App
    Log.d('初始化的时候注册微信AppId');
    await WechatKitPlatform.instance.registerApp(
      appId: kWechatAppID,
      universalLink: kWechatUniversalLink,
    );
  }

  /// 用户授权登录
  void loginWithWX(WXInfoCallback callback) async {
    mWXInfoCallback = callback;

    if (_respSubs == null) {
      await _initWX();
    }

    await WechatKitPlatform.instance.auth(
      scope: <String>[WechatScope.kSNSApiUserInfo],
      state: 'auth',
    );
  }

  /// 分享到微信
  void shareWithWX(String message) async {
    if (_respSubs == null) {
      await _initWX();
    }

    WechatKitPlatform.instance.shareText(
      scene: WechatScene.kSession, //分享朋友
      text: message,
    );
  }

  /// 是否安装微信
  Future<bool> isInstallWX() async {
    if (_respSubs == null) {
      await _initWX();
    }

    return WechatKitPlatform.instance.isInstalled();
  }

  void _listenResp(WechatResp resp) {
    if (resp is WechatAuthResp) {
      _authResp = resp;
      final String content = 'auth: ${resp.errorCode} ${resp.errorMsg}';
      if (resp.errorCode == 0) {
        //登录成功之后获取微信详用户情信息
        fetchWXInfo();
      } else if (resp.errorCode == -2) {
        _showTips('登录取消', content);
      } else if (resp.errorCode == -4) {
        _showTips('登录失败', content);
      }
    } else if (resp is WechatShareMsgResp) {
      final String content = 'share: ${resp.errorCode} ${resp.errorMsg}';
      _showTips('分享', content);
    } else if (resp is WechatPayResp) {
      final String content = 'pay: ${resp.errorCode} ${resp.errorMsg}';
      _showTips('支付', content);
    } else if (resp is WechatLaunchMiniProgramResp) {
      final String content = 'mini program: ${resp.errorCode} ${resp.errorMsg}';
      _showTips('拉起小程序', content);
    }
  }

  void fetchWXInfo() async {
    if (_authResp != null && _authResp!.isSuccessful) {
      //先拿到AccessToken，得到其中的openid与accessToken才能获取详细信息
      final WechatAccessTokenResp accessTokenResp = await WechatExtension.getAccessTokenUnionID(
        appId: kWechatAppID,
        appSecret: kWechatAppSecret,
        code: _authResp!.code!,
      );

      if (accessTokenResp.isSuccessful) {
        _showTips("获取用户成功", "openid:${accessTokenResp.openid!} accessToken:${accessTokenResp.accessToken}");
        mWXInfoCallback?.call(accessTokenResp.openid!);
      } else {
        _showTips("获取用户信息", "失败了");
      }
    }
  }

  void _showTips(String action, String content) {
    Log.d("操作：$action 内容：$content");
  }
}
